<template>
    <div>
        <div id="title">
            <panle title="机构管理" content=""></panle>
        </div>
        <div id="search" class="pt20">
            <Search
                    @setSearchForm="setSearchForm"
                    @changeSearchForm="changeSearchForm"
                    @setExport="setExport"
                    :searchForm="searchForm"
                    :searchFormObject="searchFormObject"
                    :searchOptions="searchOptions"
                    :exportOptions="true"
            ></Search>
        </div>
        <div id="searchbar" class="pt20">
            <el-button size="mini" @click="init()">刷新</el-button>
            <PersButton
                    type="primary"
                    size="mini"
                    perms="initial:institution:add"
                    label="添加"
                    @click="add"
            ></PersButton>
        </div>

        <div id="body">
            <el-table
                    :data="tableData"
                    border
                    ref="container"
                    style="width: 100%"
            >
                <el-table-column
                        :key="index"
                        v-for="(item, index) in fieldList"
                        :prop="item.field_name"
                        :label="item.show_name"
                        align="center"
                        v-if="item.is_show"
                >
                    <template slot-scope="scope">
                        <template v-if="item.field_name == 'supervise'">
                            <span v-if="scope.row.supervise == 1">筛查机构</span>
                            <span v-else>管理机构</span>
                        </template>
                        <template v-else-if="item.field_name == 'years'">
                            {{ scope.row[item.field_name] }}
                        </template>
                        <template v-else>{{ scope.row[item.field_name] }}</template>
                    </template>
                </el-table-column>

                <el-table-column fixed="right" label="操作">
                    <template slot="header" slot-scope="scope">
                        <span>操作</span>
                        <el-popover class="upload-demo" trigger="click" width="100">
                            <div :key="index" v-for="(item, index) in fieldList">
                                <el-checkbox
                                        @change="(checked) => checkBoxStatus(checked, item)"
                                        v-if="item.is_show == 1"
                                        :checked="true"
                                >{{ item.show_name }}
                                </el-checkbox>
                                <el-checkbox
                                        @change="(checked) => checkBoxStatus(checked, item)"
                                        v-else
                                >
                                    {{ item.show_name }}
                                </el-checkbox>
                            </div>
                            <i
                                    class="el-icon-setting"
                                    slot="reference"
                                    style="padding-left: 10px"
                            ></i>
                        </el-popover>
                    </template>
                    <template #default="scope">
                        <PersButton
                                type="warning"
                                size="mini"
                                label="修改"
                                icon="fa  fa-pencil"
                                perms="initial:institution:edit"
                                @click="edit(scope.row)"
                        ></PersButton>
                        <PersButton
                                type="danger"
                                size="mini"
                                icon="el-icon-delete"
                                perms="initial:institution:del"
                                label="删除"
                                @click="del(scope.row)"
                        ></PersButton>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div id="page">
            <el-pagination
                    :page-sizes="['10', '20', '50', '100']"
                    :total="total"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    background
                    layout="total, sizes, prev, pager, next, jumper"
            >
            </el-pagination>
        </div>
        <el-dialog
                v-dialogDrag
                :visible.sync="dialogOpen"
                width="90%"
                append-to-body
                :title="dialogStatus === 'create' ? '新增' : '修改'"
        >
            <create
                    v-if="dialogOpen"
                    @childByDialogVisible="childByDialogVisible"
                    :dialogStatus="dialogStatus"
                    :rowData="dataParameter"
            ></create>
        </el-dialog>
    </div>
</template>

<script>
    import Panle from '@/components/Panle';
    import PersButton from '@/components/PersButton';
    import {fieldList, fieldUpdate} from "@/api/field/field";
    import {listInstitution, removeInstitution} from '@/api/institution/institution';
    import {listTask} from "@/api/task/task";
    import {allRegion} from "@/api/region/region";
    import Search from "@/components/common/search";
    import Create from "./create";

    let PAGE_TYPE_NAME = "institution";
    export default {
        components: {PersButton, Panle, Search, Create},
        data() {
            return {
                searchOptions: {
                    province_id: false,
                    city_id: false,
                    district_id: false,
                    institution_id: false,
                },
                searchForm: {
                    province_id: "",
                    city_id: "",
                    district_id: "",
                    institution_id: "",
                    supervise: "",
                    years: "",
                    name: "",
                },
                searchFormObject: [
                    {
                        label: "省份",
                        field: "province_id",
                        type: "select",
                        options: [],
                    },
                    {
                        label: "城市",
                        field: "city_id",
                        type: "select",
                        options: [],
                    },
                    {
                        label: "区县",
                        field: "district_id",
                        type: "select",
                        options: [],
                    },
                    {
                        label: "机构类型",
                        field: "supervise",
                        type: "select",
                        options: [
                            {
                                id: "1",
                                name: "筛查机构",
                            },
                            {
                                id: "2",
                                name: "管理机构",
                            },
                        ],
                    },
                    {
                        label: "筛查年度",
                        field: "years",
                        type: "select",
                        options: [],
                    },
                    {
                        label: "机构名称",
                        field: "name",
                        type: "input",
                        options: {},
                    },
                ],
                pageSize: 10, //一页显示多少条
                total: 0,
                pageNumber: 1,
                dataParameter: {},
                multipleSelection: [],
                dialogOpen: false,
                dialogStatus: "create",
                fieldList: [],
                tableData: [],
                provinceList: [],
                cityList: [],
                countyList: [],
                taskList: [],
            };
        },
        created() {
            this.getFieldList();
            this.getListTask();
            this.getProvinceList();
        },
        activated() {
            this.init();
        },
        filters: {},
        methods: {
            init() {
                let role = this.$store.state.member.role;
                //省级
                if (role == 7) {
                    this.searchForm.province_id = parseInt(this.$store.state.member.member.province_id);
                    this.searchOptions.province_id = true;
                } else if (role == 11) {    //市级
                    this.searchForm.province_id = parseInt(this.$store.state.member.member.province_id);
                    this.searchForm.city_id = parseInt(this.$store.state.member.member.city_id);
                    this.searchOptions.province_id = true;
                    this.searchOptions.city_id = true;
                } else if (role == 12) {    //区县级
                    this.searchForm.province_id = parseInt(this.$store.state.member.member.province_id);
                    this.searchForm.city_id = parseInt(this.$store.state.member.member.city_id);
                    this.searchForm.district_id = parseInt(this.$store.state.member.member.district_id);
                    this.searchOptions.province_id = true;
                    this.searchOptions.city_id = true;
                    this.searchOptions.district_id = true;
                } else if (role == 6 || role == 8 || role == 9 || role == 10) {
                    //筛查人员
                    this.searchForm.province_id = parseInt(this.$store.state.member.member.province_id);
                    this.searchForm.city_id = parseInt(this.$store.state.member.member.city_id);
                    this.searchForm.district_id = parseInt(this.$store.state.member.member.district_id);
                    this.searchForm.institution_id = parseInt(this.$store.state.member.institution_id);
                    this.searchOptions.province_id = true;
                    this.searchOptions.city_id = true;
                    this.searchOptions.district_id = true;
                    this.searchOptions.institution_id = true;
                }
                this.list();
            },
            list() {
                this.loading = true;
                let param = {
                    pageSize: this.pageSize,
                    page: this.page,
                    province_id: this.searchForm.province_id,
                    city_id: this.searchForm.city_id,
                    district_id: this.searchForm.district_id,
                    institution_id: this.searchForm.institution_id,
                    supervise: this.searchForm.supervise,
                    years: this.searchForm.years,
                    name: this.searchForm.name,
                }
                listInstitution(param).then((res) => {
                    if (res.code === 200) {
                        this.tableData = res.data.data;
                        this.total = res.data.total;
                        this.loading = false;
                    } else {
                        this.msgError(res.msg);
                    }
                })
            },
            getProvinceList() {
                let param = {
                    pid: 1
                }
                allRegion(param).then((res) => {
                    if (res.code === 200) {
                        this.provinceList = res.data;
                    } else {
                        this.msgError(res.msg);
                    }
                })
            },
            getCityList() {
                let param = {
                    pid: this.searchForm.province_id
                }
                allRegion(param).then((res) => {
                    if (res.code === 200) {
                        this.cityList = res.data;
                    } else {
                        this.msgError(res.msg);
                    }
                })
            },
            getCountyList() {
                let param = {
                    pid: this.searchForm.city_id
                }
                allRegion(param).then((res) => {
                    if (res.code === 200) {
                        this.countyList = res.data;
                    } else {
                        this.msgError(res.msg);
                    }
                })
            },
            getListTask() {
                let param = {
                    pageSize: 100,
                    page: 1,
                }
                listTask(param).then((res) => {
                    if (res.code === 200) {
                        console.log(res.data.data)
                        this.taskList = res.data.data;
                    } else {
                        this.msgError(res.msg);
                    }
                })
            },
            //获取字段列表
            getFieldList() {
                fieldList({action_name: PAGE_TYPE_NAME})
                    .then((result) => {
                        this.fieldList = result.data;
                    })
                    .catch((err) => {
                        console.log("err", err);
                    });
            },
            // 当点击checkbox时改变字段显示和隐藏
            checkBoxStatus(checked, row) {
                let params = JSON.parse(JSON.stringify(row));
                params.is_show = checked ? 1 : 0;
                fieldUpdate(params)
                    .then((result) => {
                        this.getFieldList();
                    })
                    .catch((err) => {
                        console.log("err", err);
                    });
            },
            setSearchForm(searchForm) {
                this.searchForm = searchForm;
                this.init();
            },
            setExport(searchForm) {
                this.searchForm = searchForm;
                this.exportData();
            },
            changeSearchForm(searchForm) {
                this.searchForm = searchForm;
            },
            handleSizeChange(e) {
                this.pageSize = e;
                this.init();
            },
            handleCurrentChange(e) {
                this.page = e;
                this.init();
            },
            //多选
            handleSelectionChange(e) {
                let selectChang = []
                for (let item of e) {
                    selectChang.push(item.id)
                }
                this.multipleSelection = selectChang;
            },
            //添加
            add() {
                this.dialogOpen = true
                this.dialogStatus = 'create'
            },
            //修改
            edit(row) {
                this.dialogOpen = true
                this.dialogStatus = 'update'
                this.dataParameter = row;
            },
            //删除
            del(data) {
                console.log(data, '删除')
                this.$confirm('确定删除【' + data.institution_name + '】', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    console.log(data)
                    removeInstitution(data).then((res) => {
                        if (res.code === 200) {
                            this.msgSuccess(res.msg);
                            this.init();
                        } else {
                            this.msgError(res.msg);
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //批量删除
            delAll() {
                if (this.multipleSelection.length < 1) {
                    this.msgError("请选择数据");
                } else {
                    let ids = this.multipleSelection.join(",");
                    this.$confirm('确定删除【' + ids + '】', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.multipleSelection.forEach((item) => {
                            removeInstitution({id: item}).then((res) => {
                                if (res.code === 200) {
                                    this.msgSuccess(res.msg);
                                    this.init();
                                } else {
                                    this.msgError(res.msg);
                                }
                            })
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            //对话框点击确定后的回调事件
            childByDialogVisible(childValue, isUpdate) {
                this.dialogOpen = childValue
                this.dataParameter = ""
                if (isUpdate) {
                    this.init()
                }
            },
            //数据导出
            exportData() {
                //下载数据
                let params = {
                    province_id: this.searchForm.province_id,
                    city_id: this.searchForm.city_id,
                    district_id: this.searchForm.district_id,
                    institution_id: this.searchForm.institution_id,
                    supervise: this.searchForm.supervise,
                    years: this.searchForm.years,
                    name: this.searchForm.name,
                };
                window.location.href = this.setQueryPath(
                    process.env.VUE_APP_API + "/initial/institution/excelExport",
                    params
                );
            },
            setQueryPath(url, queryData) {
                var _str = "";
                for (var o in queryData) {
                    _str += o + "=" + queryData[o] + "&";
                }
                var _str = _str.substring(0, _str.length - 1);
                return url + "?" + _str;
            },
        },
        watch: {
            "taskList"(newVal, oldVal) {
                if (oldVal !== newVal && typeof newVal == "object") {
                    console.log(this.searchFormObject)
                    newVal.forEach((e) => {
                        this.searchFormObject[4].options.push({name: e.years, id: e.years,});
                    })
                }
            },
            "searchForm.province_id"(newVal, oldVal) {
                if (oldVal !== newVal) {
                    console.log(newVal)
                    if (newVal == "") {
                        this.searchForm.city_id = "";
                        this.searchForm.district_id = "";
                    } else {
                        this.getCityList();
                    }
                }
            },
            "searchForm.city_id"(newVal, oldVal) {
                if (oldVal !== newVal) {
                    if (newVal == "") {
                        this.searchForm.district_id = "";
                    } else {
                        this.getCountyList();
                    }
                }
            },
            "provinceList"(newVal, oldVal) {
                if (oldVal !== newVal && typeof newVal == "object") {
                    newVal.forEach((e) => {
                        this.searchFormObject[0].options.push({id: e.id, name: e.district});
                    })
                }
            },
            "cityList"(newVal, oldVal) {
                if (oldVal !== newVal && typeof newVal == "object") {
                    this.searchFormObject[1].options = [];
                    newVal.forEach((e) => {
                        this.searchFormObject[1].options.push({id: e.id, name: e.district});
                    })
                }
            },
            "countyList"(newVal, oldVal) {
                if (oldVal !== newVal && typeof newVal == "object") {
                    this.searchFormObject[2].options = [];
                    newVal.forEach((e) => {
                        this.searchFormObject[2].options.push({id: e.id, name: e.district});
                    })
                }
            },
        },
    }

</script>
<style lang="scss" scoped="scoped">
    #search,
    #body,
    #functional,
    #page {
        padding-top: 20px;
    }

    .el-col {
        margin-left: 15px;
    }

    .addbutton {
        margin-left: -20px;
    }

    div.el-form-item__content {
        width: 100% !important;
    }
</style>

